#include "menudialog.h"
#include "ui_menudialog.h"

MenuDialog::MenuDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MenuDialog)
{
    ui->setupUi(this);
    DictEdit::InitializeDictionary();
    BotAndSocket = new QMap<QString, QListWidgetItem>();

    connect(&botServer, SIGNAL(MsgUpdating(QString)), this, SLOT(setNewMsg(QString)));
    connect(&botServer, SIGNAL(SocketListUpdate(QList<int>)), this, SLOT(UpdateSocketList(QList<int>)));
    connect(ui->lstBots, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(openBotWindow(QModelIndex)));

    if (!botServer.listen(QHostAddress::Any, 80)) {
        ui->lblStatus->setText(tr("Unable to start the server: %1.").arg(botServer.errorString()));
    }else
    {
         ui->lblStatus->setText(tr("Listening..."));
    }
}

MenuDialog::~MenuDialog()
{
    delete ui;
    delete configuration;
    delete itmBot;
}

void MenuDialog::setNewMsg(QString newMsg)
{
    switch(newMsg.at(0).toLatin1())
    {
        case EnMsg_CONFIG:  configuration = new ConfigParser();
                            configuration->msgParse(newMsg);
                            AddBot(configuration);
                            qDebug() << "Received a Configuration Message";
                            break;
        default:
            qDebug() << "Invalid Message Received from Connecting Client";
    }
}

void MenuDialog::AddBot(ConfigParser* configuration)
{
    QString descipt = configuration->getID() + " : " + BotLookUp.value(configuration->getBotType().at(0).toLatin1());
    itmBot = new QListWidgetItem(descipt);
    itmBot->setTextAlignment(Qt::AlignHCenter);
    itmBot->setForeground(Qt::green);
    itmBot->setBackground(Qt::black);

    BotAndSocket->insert(configuration->getSocketID(), *itmBot);
    UpdateList();
}

void MenuDialog::openBotWindow(QModelIndex modelIndex)
{
    qDebug() << "Opening = " << modelIndex.data().toString();
    BotWindow = new MainWindow();
    BotWindow->setWindowTitle(modelIndex.data().toString());
    BotWindow->show();
    exec();
}

void MenuDialog::UpdateSocketList(QList<int> newSocketList)
{
    socketList = new QList<int>(newSocketList);
    qDebug() << "$Socket List being updated!:" << *socketList;
    ui->lblDeviceCount->setText(QString::number(socketList->count()));

    for(int i = 0; i < BotAndSocket->count(); i++)
    {
        if(!socketList->contains(BotAndSocket->keys().at(i).toInt()))
        {
            BotAndSocket->remove(BotAndSocket->keys().at(i));
        }
    }

    UpdateList();
}

void MenuDialog::UpdateList()
{
    ui->lstBots->clear();
    for(int i = 0; i < BotAndSocket->count(); i++)
    {
        ui->lstBots->addItem(new QListWidgetItem(BotAndSocket->values().at(i)));
    }
}
